package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.config.TanhuaConfig;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;


//    @Value("${tanhua.default.user}")
//    private Long defaultUser; //TODO 默认推荐用户，这里建议写到nacos中          完成
//
//    @Value("${tanhua.default.user.list}")
//    private Long[] defaultUserList; //TODO 默认推荐用户，这里建议写到nacos中    完成


    @Autowired
    private TanhuaConfig tanhuaConfig;


    public Object queryTodayBest() {
        Long userId = UserThreadLocal.get();

        //查询得分最高的人
        RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
        if (null == recommendUser) {
            //给出一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(this.tanhuaConfig.getUser());
            recommendUser.setToUserId(userId);
            recommendUser.setScore(RandomUtil.randomDouble(80, 99));
        }

        //查询用户信息，封装成TodayBest对象返回
        UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());

        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        todayBest.setFateValue(recommendUser.getScore().longValue());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());

        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param queryParam
     * @return
     */
    public Object queryRecommendation(RecommendUserQueryParam queryParam) {
        Long userId = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        //通过dubbo服务查询推荐用户列表
        PageInfo<RecommendUser> pageInfo = this.recommendUserApi.queryPageInfo(userId, queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            records = new ArrayList<>();
            //给出默认的推荐用户
            for (Long uid : this.tanhuaConfig.getList()) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(uid);
                recommendUser.setToUserId(userId);
                recommendUser.setScore(RandomUtil.randomDouble(80, 99));
                records.add(recommendUser);
            }
        }

        //查询用户信息列表
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");

        //TODO 根据条件筛选用户数据  完成
        List<UserInfo> userInfoList = this.userInfoApi
                .queryByRecommendUser(userIdList,
                        queryParam.getAge(),
                        queryParam.getCity());
        if(CollUtil.isEmpty(userInfoList)){
            return pageResult;
        }
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setId(userInfo.getUserId());

            // 查找到该用户所对应的RecommendUser对象，目的是获取它的得分
            for (RecommendUser record : records) {
                if(ObjectUtil.equal(record.getUserId(), userInfo.getUserId())){
                    todayBest.setFateValue(record.getScore().longValue());
                    break;
                }
            }

            todayBestList.add(todayBest);
        }

        //TODO 排序 完成
        Collections.sort(todayBestList, (o1, o2) -> {
            return (int) (o2.getFateValue() - o1.getFateValue());
        });



        pageResult.setItems(todayBestList);
        return pageResult;
    }
}
